package com.rh.soc.sysconfigthirdinterface.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rh.soc.comm.AckState;
import com.rh.soc.management.systemconfig.serviceconfig.model.DnsServiceVO;
import com.rh.soc.management.systemconfig.serviceconfig.model.ServiceConfigVO;
import com.rh.soc.management.systemconfig.serviceconfig.model.StmMsgConfigVO;
import com.rh.soc.management.systemconfig.serviceconfig.service.IServiceConfigService;
import com.rh.soc.sysconfigthirdinterface.model.ThirdCodeListVO;
import com.rh.webserver.common.base.bean.AppResultBean;
import com.rh.webserver.common.base.controller.BaseController;
import com.rh.webserver.common.base.exception.AppException;
import com.rh.webserver.common.base.json.IDataCenter;
import com.rh.webserver.common.base.mail.model.MailConfigVO;
import com.rh.webserver.common.util.BeanUtils;
import com.rh.webserver.common.util.StringUtil;

@Controller
@RequestMapping("/third/sysconfig")
public class SysConfigController extends BaseController {

	private Logger logger = Logger.getLogger(error);

	@Resource
	IServiceConfigService ServiceConfigIA;

	/**
	 * 
	 * 修改邮件服务信息
	 * 
	 */
	@RequestMapping("/updMailServiceInfo")
	@ResponseBody
	public AppResultBean updMailServiceInfo(@RequestParam("param") String param, HttpSession session) throws Exception {
		logger.info("param=["+param+"]");
		IDataCenter idc = BeanUtils.toDataCenter(param);
		AppResultBean bean = new AppResultBean();
		List<ThirdCodeListVO> mailInfoList = (List<ThirdCodeListVO>) BeanUtils.jsonToBeans(idc, "mailInfo", ThirdCodeListVO.class);
		MailConfigVO vo =changeCodeListToMailConfigVO(mailInfoList);
		try {
			int rtn = ServiceConfigIA.updMailServiceInfo(vo);
			if (rtn == 1) {
				bean.ok("修改邮件服务器同步成功。");
			} else {
				bean.fail("修改邮件服务器同步失败。");
			}
		} catch (AppException e) {
			logger.error("修改邮件服务器同步失败。", e);
			bean.fail("修改邮件服务器同步失败。");
		}
		return bean;
	}

	private MailConfigVO changeCodeListToMailConfigVO(List<ThirdCodeListVO> thirdCodeList){
		MailConfigVO mailConfigVO=new MailConfigVO();
		
		Map<String,String> map=new HashMap<String,String>();
		for(int i=0;i<thirdCodeList.size();i++){
			String code=thirdCodeList.get(i).getCode();
			String name=thirdCodeList.get(i).getName();
			map.put(code, name);
		}
		
		if(map.containsKey("EMAIL_HOST")){
			mailConfigVO.setSendHost(map.get("EMAIL_HOST"));
		}
		
		if(map.containsKey("EMAIL_USERNAME")){
			String from=map.get("EMAIL_USERNAME");
			String fromUser=map.get("EMAIL_USERNAME").split("@")[0];
			mailConfigVO.setFrom(from);
			mailConfigVO.setUsername(fromUser);
		}
		
		if(map.containsKey("EMAIL_PASSWORD")){
			String emailPassword=map.get("EMAIL_PASSWORD");
			if(StringUtil.isNotEmpty(emailPassword)){
				mailConfigVO.setPassword(emailPassword);
				mailConfigVO.setNeedAuth("1");
			}
			else{
				mailConfigVO.setNeedAuth("0");
			}
		}
		else{
			mailConfigVO.setNeedAuth("0");
		}
				
		if(map.containsKey("EMAIL_USESSL")){
			String ssl= map.get("EMAIL_USESSL");
			if(ssl.equals("1")){
				mailConfigVO.setSsl("1");
				mailConfigVO.setSendPort(Integer.valueOf(map.get("EMAIL_SSLPORT")));
			}
			else{
				mailConfigVO.setSsl("0");
				mailConfigVO.setSendPort(Integer.valueOf(map.get("EMAIL_PORT")));
			}
		}
		
		
		return mailConfigVO;
		
	}

	/**
	 * 初始化服务配置页面，包括DNS服务配置、邮件服务配置、NTP校时配置信息
	 */
	@RequestMapping("/getconfig")
	@ResponseBody
	public AppResultBean jumpToServiceConfig(@RequestParam("param") String param, HttpSession session)
			throws Exception {
		AppResultBean bean = new AppResultBean();
		/** 得到邮件服务的相关信息 */
		List<MailConfigVO> mailResult = new ArrayList<MailConfigVO>();
		try {
			mailResult = ServiceConfigIA.queryMailConfigInfo();
		} catch (AppException e) {
			logger.error("获取邮件信息失败", e);
			bean.fail("获取数据失败。");
		}
		setStoreRowData(bean, "mailservicestore", mailResult);

		/** 得到 DNS 相关信息 */
		List<DnsServiceVO> dnsResult = new ArrayList<DnsServiceVO>();
		try {
			dnsResult = ServiceConfigIA.queryDnsConfigInfo();
		} catch (AppException e) {
			logger.error("获取DNS信息失败", e);
			bean.fail("获取数据失败。");
		}
		setStoreRowData(bean, "dnsstore", dnsResult);

		/** 得到 NTP 相关信息 */
		List<ServiceConfigVO> ntpResult = new ArrayList<ServiceConfigVO>();
		try {
			ntpResult = ServiceConfigIA.queryServiceConfigInfo();
		} catch (AppException e) {
			logger.error("获取 NTP信息失败", e);
			bean.fail("获取数据失败。");
		}
		setStoreRowData(bean, "ntpstore", ntpResult);

		/** 短信配置 相关信息 */
		StmMsgConfigVO vo = new StmMsgConfigVO();
		try {
			vo = ServiceConfigIA.showSMSConfig();
		} catch (AppException e) {
			logger.error("读取短信配置信息失败", e);
			bean.fail("读取短信配置信息失败。");
		}
		setStoreRowData(bean, "smsstore", vo);
		return bean;

	}

	/**
	 * 
	 * 修改DNS服务器配置
	 * 
	 */
	@RequestMapping("/updDnsServiceInfo")
	@ResponseBody
	public AppResultBean updDnsServiceInfo(@RequestParam("param") String param, HttpSession session) throws Exception {
		IDataCenter idc = BeanUtils.toDataCenter(param);
		DnsServiceVO vo = (DnsServiceVO) BeanUtils.jsonToBean(idc, DnsServiceVO.class);
		AppResultBean bean = new AppResultBean();
		try {
			int rtn = ServiceConfigIA.updDnsServiceInfo(vo);
			if (rtn == 1) {
				bean.ok("保存成功。");
			} else {
				bean.fail("保存失败。");
			}
		} catch (AppException e) {
			logger.error("DNS 保存发生异常", e);
			bean.fail("保存失败。");
		}
		return bean;
	}

	/**
	 * 
	 * 修改NTP校时信息
	 * 
	 */
	@RequestMapping("/updNtpServiceInfo")
	@ResponseBody
	public AppResultBean updServiceConfigInfo(@RequestParam("param") String param, HttpSession session)
			throws Exception {
		IDataCenter idc = BeanUtils.toDataCenter(param);
		ServiceConfigVO vo = (ServiceConfigVO) BeanUtils.jsonToBean(idc, ServiceConfigVO.class);
		AppResultBean bean = new AppResultBean();
		try {
			int returnValue = ServiceConfigIA.updServiceConfigInfo(vo);
			int rtn = ServiceConfigIA.configNtp();
			if ((returnValue == 1) && (rtn > 0)) {
				bean.ok("保存成功。");
			} else if ((returnValue == 1) && (rtn < 0)) {
				bean.fail("保存成功，通知后台定时任务失败。");
			} else {
				bean.fail("保存失败。");
			}
		} catch (AppException e) {
			logger.error("NTP 保存失败", e);
			bean.fail("保存失败。");
		}
		return bean;
	}

	/**
	 * 
	 * 手动设置系统时间
	 * 
	 */
	@RequestMapping("/manualSetSystemTime")
	@ResponseBody
	public AppResultBean manualSetSystemTime(@RequestParam("param") String param, HttpSession session)
			throws Exception {
		AppResultBean bean = new AppResultBean();
		IDataCenter idc = BeanUtils.toDataCenter(param);
		ServiceConfigVO vo = (ServiceConfigVO) BeanUtils.jsonToBean(idc, ServiceConfigVO.class);
		try {
			int returnValue = ServiceConfigIA.manualSetSystemTime(vo.getManualSettingTime());
			if (returnValue == 1) {
				bean.ok("设置成功。");
			} else {
				bean.fail("设置失败。");
			}
		} catch (Exception e) {
			logger.error("手动设置系统时间出现异常", e);
			bean.fail("设置失败。");
		}
		return bean;
	}

	/**
	 * 
	 * 测试邮件服务
	 * 
	 */
	@RequestMapping("/checkMailService")
	@ResponseBody
	public AppResultBean checkMailService(@RequestParam("param") String param, HttpSession session) {
		logger.info("checkMailService: " + param);
		AppResultBean bean = new AppResultBean();
		try {
			IDataCenter idc = BeanUtils.toDataCenter(param);
			MailConfigVO vo = (MailConfigVO) BeanUtils.jsonToBean(idc, MailConfigVO.class);
			int rtn = ServiceConfigIA.checkMailService(vo);
			if (rtn == 1) {
				bean.ok("测试成功。");
			} else {
				bean.fail("测试失败。");
			}
		} catch (Exception e) {
			logger.error("测试邮件服务器失败", e);
			bean.fail("测试失败。");
		}
		return bean;
	}

	/**
	 * 
	 * 测试NTP校时
	 * 
	 */
	@RequestMapping("/checkNtpService")
	@ResponseBody
	public AppResultBean checkServiceConfig(@RequestParam("param") String param, HttpSession session) throws Exception {
		IDataCenter idc = BeanUtils.toDataCenter(param);
		/** 在这个 VO 中只有一个字段是不用的 即 manualSettingTime */
		ServiceConfigVO serviceConfigVo = (ServiceConfigVO) BeanUtils.jsonToBean(idc, ServiceConfigVO.class);
		AppResultBean bean = new AppResultBean();
		try {
			int returnValue = ServiceConfigIA.checkServiceConfig(serviceConfigVo);
			if (returnValue == 1) {
				bean.ok("测试成功。");
			} else {
				bean.fail("测试失败。");
			}
		} catch (AppException e) {
			logger.error("测试NTP服务器失败", e);
			bean.fail("测试失败。");
		}
		return bean;
	}

	/**
	 * 
	 * 同步NTP校时
	 * 
	 */
	@RequestMapping("/synchroServiceConfig")
	@ResponseBody
	public AppResultBean synchroServiceConfig(@RequestParam("param") String param, HttpSession session)
			throws Exception {
		IDataCenter idc = BeanUtils.toDataCenter(param);
		/** 在这个 VO 中只有一个字段是不用的 即 manualSettingTime */
		ServiceConfigVO serviceConfigVo = (ServiceConfigVO) BeanUtils.jsonToBean(idc, ServiceConfigVO.class);
		AppResultBean bean = new AppResultBean();
		try {
			int returnValue = ServiceConfigIA.synchroServiceConfig(serviceConfigVo);
			if (returnValue == 1) {
				bean.ok("同步成功。");
			} else {
				logger.error("同步失败。");
				bean.fail("同步失败。");
			}
		} catch (AppException e) {
			logger.error("同步NTP校时失败", e);
			bean.fail("同步失败。");
		}
		return bean;
	}

	/**
	 * 
	 * 读取短信配置初始化信息
	 * 
	 */
	@RequestMapping("/getSMSConfig")
	@ResponseBody
	public AppResultBean showSMSConfig(@RequestParam("param") String param, HttpSession session) throws Exception {
		AppResultBean bean = new AppResultBean();
		StmMsgConfigVO vo = new StmMsgConfigVO();
		try {
			vo = ServiceConfigIA.showSMSConfig();
			bean.ok(vo);
		} catch (AppException e) {
			logger.error("读取短信配置信息失败", e);
			bean.fail("读取短信配置信息失败。");
		}
		return bean;
	}

	/**
	 * 
	 * 保存短信配置信息
	 * 
	 */
	@RequestMapping("/saveSMSConfig")
	@ResponseBody
	public AppResultBean saveSMSConfig(@RequestParam("param") String param, HttpSession session) throws Exception {
		IDataCenter idc = BeanUtils.toDataCenter(param);
		String result = "";
		AppResultBean bean = new AppResultBean();
		try {
			StmMsgConfigVO serviceConfigVo = (StmMsgConfigVO) BeanUtils.jsonToBean(idc, StmMsgConfigVO.class);
			// Map<String, String> params = idc.getParameters();
			// if (params != null) {
			// String configType = params.get("configType");
			// serviceConfigVo.setConfigType(configType);
			// }

			AckState flag = ServiceConfigIA.saveSMSConfig(serviceConfigVo);
			if ("DatabaseError".equals(flag.toString())) {
				result = "数据库错误。";
			} else if ("Fail".equals(flag.toString())) {
				result = "操作不成功。";
			} else if ("IllegalArgument".equals(flag.toString())) {
				result = "参数错误。";
			} else if ("InternalError".equals(flag.toString())) {
				result = "系统内部错误。";
			} else if ("LicenseError".equals(flag.toString())) {
				result = "License检查错误。";
			} else if ("NetworkError".equals(flag.toString())) {
				result = "网络异常。";
			} else if ("Success".equals(flag.toString())) {
				result = "短信配置操作成功。";
				bean.ok(result);
				return bean;
			} else if ("Warning".equals(flag.toString())) {
				result = "操作不成功，但不影响系统运行。";
			}
			bean.fail(result);
		} catch (AppException e) {
			logger.error("保存短信配置信息失败", e);
			bean.fail(e.getMessage());
		}
		return bean;
	}
}
